package com.sscl.blelibrary;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;

import java.util.Arrays;

/**
 * @author jackie
 */
public final class AdvertiseData {

    /**
     * The max data size to be advertised (27 bytes);
     * advertising data can't be more than 31 bytes ,but we only can use 29 bytes
     * start of 2 bytes is manufacturerId
     * then we can use 27 bytes for data( total 29 bytes)
     * for example: you want to advertise the data "01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29"
     * you shout set manufacturerId to "02 01"(for int value is 513,HEX vale 0x0201) and set data to "03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29"
     */
    public static final int MAX_ADVERTISE_DATA_LENGTH = 29;

    private final int manufacturerId;
    private final byte[] data;

    public AdvertiseData(@IntRange(from = 0, to = 0xFFFF) int manufacturerId, byte[] data) {
        this.manufacturerId = manufacturerId;
        this.data = data;
    }

    public int getManufacturerId() {
        return manufacturerId;
    }

    public byte[] getData() {
        return data;
    }

    @NonNull
    @Override
    public String toString() {
        byte[] bytes = BleManager.intToByteArrayLength2(manufacturerId);
        revertData(bytes);
        byte[] result = new byte[bytes.length + data.length];
        System.arraycopy(bytes, 0, result, 0, bytes.length);
        System.arraycopy(data, 0, result, bytes.length, data.length);
        return "AdvertiseData{" +
                "manufacturerId=" + manufacturerId +
                ", data=" + BleManager.byteArrayToHexStr(data) +
                '}' + "\nparse to hex bytes array:" + BleManager.byteArrayToHexStr(result);
    }

    /**
     * 将数据反转
     *
     * @param array 原始数据
     */
    private void revertData(byte[] array) {
        for (int i = 0; i < array.length / 2; i++) {
            //交换在位置array.length-i和index上的两个数
            byte temp = array[array.length - 1 - i];
            array[array.length - 1 - i] = array[i];
            array[i] = temp;
        }
    }
}
